<template>
  <div :id="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts';
require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/util/util'

export default {
  props: {
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100px'
    },
    className: {
      type: String,
      default: 'chart'
    },
    visitorData: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      let dataLabel = [],  dataValue = []
      this.visitorData.forEach(element => {
        dataLabel.push(element.name)
        dataValue.push(element.value)
      });
      this.chart = echarts.init(this.$el, 'macarons')
      this.chart.setOption({
        grid: {
          top: 10,
          bottom: 30,
          left: 50,
          right: 20
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dataLabel,
          splitLine: {
            lineStyle: {
              color: ['#666666']
            }
          },
          axisLine: {
            lineStyle: {
              color: '#ffffff',
            }
          }
        },
        yAxis: {
          type: 'value',
          interval: 1000,
          splitLine: {
            lineStyle: {
              color: ['#666666']
            }
          },
          axisLine: {
            lineStyle: {
              color: '#ffffff',
            }
          }
        },
        series: [
          {
            type: 'line',
            data: dataValue,
            lineStyle: {
              color: '#5b8ff8'
            },
            areaStyle: {
              color: '#5b8ff8',
              opacity: 0.3
            }
          }
        ]
      })
    }
  }
}
</script>
